<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import materialCategoryApi from '@/api/materialCategory';
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import CommonLayout from '../components/CommonLayout.vue';

// 一级分类数据
const mainCategories = ref([]);
// 二级分类数据
const subCategories = ref([]);
// 所有分类数据(用于树形展示)
const allCategories = ref([]);
// 当前选中的分类，用于显示详情
const selectedCategory = ref(null);
// 控制详情面板的显示与隐藏
const detailVisible = ref(false);
// 控制添加/编辑对话框的显示与隐藏
const dialogVisible = ref(false);
// 对话框类型(add/edit)
const dialogType = ref('add');
// 当前操作的分类
const currentCategory = ref(null);
// 分类类型(一级/二级)
const categoryType = ref('firstLevel');
// 搜索表单
const searchForm = reactive({
  code: '',
  name: '',
  expanded: false,
  unit: '',
  serialLength: '',
  supplyMethod: '',
  status: ''
});
// 加载状态
const loading = ref(false);
// 树配置
const treeProps = {
  children: 'children',
  label: 'CategoryName'
};

// 获取一级分类数据
const fetchMainCategories = async () => {
  loading.value = true;
  try {
    const data = await materialCategoryApi.firstLevel.getAll();
    mainCategories.value = data;
    return data;
  } catch (error) {
    ElMessage.error('获取一级分类数据失败');
    console.error('获取一级分类数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取二级分类数据
const fetchSubCategories = async () => {
  loading.value = true;
  try {
    const data = await materialCategoryApi.secondLevel.getAll();
    subCategories.value = data;
    return data;
  } catch (error) {
    ElMessage.error('获取二级分类数据失败');
    console.error('获取二级分类数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 构建树形结构数据
const buildTreeData = (mainCats, subCats) => {
  // 创建一级分类映射
  const mainCatMap = new Map();
  mainCats.forEach(cat => {
    mainCatMap.set(cat.Id, { ...cat, children: [] });
  });

  // 将二级分类添加到对应的一级分类下
  subCats.forEach(subCat => {
    if (mainCatMap.has(subCat.FirstLevelCategoryId)) {
      mainCatMap.get(subCat.FirstLevelCategoryId).children.push(subCat);
    }
  });

  // 转换为数组
  return Array.from(mainCatMap.values());
};

// 获取所有分类数据(树形结构)
const fetchAllCategories = async () => {
  loading.value = true;
  try {
    const mainCats = await fetchMainCategories();
    const subCats = await fetchSubCategories();
    allCategories.value = buildTreeData(mainCats, subCats);
  } catch (error) {
    ElMessage.error('获取分类数据失败');
    console.error('获取分类数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 初始化加载数据
onMounted(async () => {
  await fetchAllCategories();
});

// 处理详情按钮点击事件
const handleDetailClick = (data) => {
  selectedCategory.value = { ...data };
  detailVisible.value = true;
};

// 搜索功能
const searchCategory = async () => {
  loading.value = true;
  try {
    // 在实际应用中，这里可能需要调用后端搜索接口
    // 为简化示例，我们直接使用本地数据过滤
    let filteredMainCats = [...mainCategories.value];
    let filteredSubCats = [...subCategories.value];
    
    // 基本搜索条件
    if (searchForm.code) {
      filteredMainCats = filteredMainCats.filter(item => item.CategoryCode?.includes(searchForm.code));
      filteredSubCats = filteredSubCats.filter(item => item.CategoryCode?.includes(searchForm.code));
    }
    
    if (searchForm.name) {
      filteredMainCats = filteredMainCats.filter(item => item.CategoryName?.includes(searchForm.name));
      filteredSubCats = filteredSubCats.filter(item => item.CategoryName?.includes(searchForm.name));
    }
    
    // 高级搜索条件
    if (searchForm.expanded) {
      if (searchForm.unit) {
        filteredSubCats = filteredSubCats.filter(item => item.Unit?.includes(searchForm.unit));
      }
      
      if (searchForm.serialLength) {
        filteredSubCats = filteredSubCats.filter(item => item.SerialLength?.toString().includes(searchForm.serialLength));
      }
      
      if (searchForm.supplyMethod) {
        filteredSubCats = filteredSubCats.filter(item => item.SupplyMethod?.includes(searchForm.supplyMethod));
      }
      
      if (searchForm.status) {
        const statusValue = searchForm.status === 'active' ? 1 : 0;
        filteredMainCats = filteredMainCats.filter(item => item.Status === statusValue);
        filteredSubCats = filteredSubCats.filter(item => item.Status === statusValue);
      }
    }
    
    allCategories.value = buildTreeData(filteredMainCats, filteredSubCats);
  } catch (error) {
    ElMessage.error('搜索分类失败');
    console.error('搜索分类失败:', error);
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = async () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  searchForm.expanded = false;
  await fetchAllCategories();
};

// 展开/收起高级搜索
const toggleAdvancedSearch = () => {
  searchForm.expanded = !searchForm.expanded;
};

// 打开添加对话框
const openAddDialog = (type = 'firstLevel') => {
  categoryType.value = type;
  dialogType.value = 'add';
  currentCategory.value = type === 'firstLevel' ? {
    CategoryCode: '',
    CategoryName: '',
    Status: 1
  } : {
    CategoryCode: '',
    CategoryName: '',
    FirstLevelCategoryId: null,
    MaterialDescription: '',
    Unit: '',
    SafetyStock: 0,
    Status: 1
  };
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (data, type) => {
  categoryType.value = type;
  dialogType.value = 'edit';
  currentCategory.value = { ...data };
  dialogVisible.value = true;
};

// 保存分类
const saveCategory = async () => {
  if (categoryType.value === 'firstLevel') {
    if (!currentCategory.value.CategoryCode || !currentCategory.value.CategoryName) {
      ElMessage.error('分类编号和分类名称不能为空');
      return;
    }
  } else {
    if (!currentCategory.value.CategoryCode || !currentCategory.value.CategoryName || !currentCategory.value.FirstLevelCategoryId) {
      ElMessage.error('分类编号、分类名称和一级分类不能为空');
      return;
    }
  }

  loading.value = true;
  try {
    const categoryToSave = { ...currentCategory.value };
    
    if (dialogType.value === 'add') {
      // 调用API添加分类
      if (categoryType.value === 'firstLevel') {
        await materialCategoryApi.firstLevel.add(categoryToSave);
      } else {
        await materialCategoryApi.secondLevel.add(categoryToSave);
      }
      ElMessage.success('添加分类成功');
    } else {
      // 调用API更新分类
      if (categoryType.value === 'firstLevel') {
        await materialCategoryApi.firstLevel.update(categoryToSave.Id, categoryToSave);
      } else {
        await materialCategoryApi.secondLevel.update(categoryToSave.Id, categoryToSave);
      }
      ElMessage.success('编辑分类成功');
    }
    
    dialogVisible.value = false;
    await fetchAllCategories();
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '添加分类失败' : '编辑分类失败');
    console.error(dialogType.value === 'add' ? '添加分类失败' : '编辑分类失败:', error);
  } finally {
    loading.value = false;
  }
};

// 切换启用/禁用状态
const toggleStatus = async (data, type) => {
  const newStatus = data.Status === 1 ? 0 : 1;
  ElMessageBox.confirm(`确定要${newStatus === 1 ? '启用' : '禁用'}该分类吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: newStatus === 1 ? 'success' : 'warning'
  }).then(async () => {
    loading.value = true;
    try {
      // 更新状态
      const updatedCategory = { ...data, Status: newStatus };
      if (type === 'firstLevel') {
        await materialCategoryApi.firstLevel.update(updatedCategory.Id, updatedCategory);
      } else {
        await materialCategoryApi.secondLevel.update(updatedCategory.Id, updatedCategory);
      }
      ElMessage.success(`分类${newStatus === 1 ? '启用' : '禁用'}成功`);
      await fetchAllCategories();
    } catch (error) {
      ElMessage.error(`分类${newStatus === 1 ? '启用' : '禁用'}失败`);
      console.error(`分类${newStatus === 1 ? '启用' : '禁用'}失败:`, error);
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 取消操作
  });
};

// 删除分类
const deleteCategory = async (data, type) => {
  // 如果是一级分类，先检查是否有相关的二级分类
  if (type === 'firstLevel') {
    loading.value = true;
    try {
      console.log('Checking second level categories for first level id:', data.Id);
      const subCategories = await materialCategoryApi.secondLevel.getByFirstLevelCategoryId(data.Id);
      if (subCategories && subCategories.length > 0) {
        ElMessage.error('该一级分类下有二级分类，无法删除');
        return;
      }
    } catch (error) {
      ElMessage.error('检查二级分类失败: ' + error.message);
      console.error('检查二级分类失败:', error);
      return;
    } finally {
      loading.value = false;
    }
  }

  ElMessageBox.confirm('确定要删除该分类吗？删除后将无法恢复。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    loading.value = true;
    try {
      // 调用API删除分类
      if (type === 'firstLevel') {
        await materialCategoryApi.firstLevel.delete(data.Id);
      } else {
        await materialCategoryApi.secondLevel.delete(data.Id);
      }
      ElMessage.success('删除分类成功');
      await fetchAllCategories();
    } catch (error) {
      ElMessage.error('删除分类失败');
      console.error('删除分类失败:', error);
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 取消删除
  });
};
</script>

<template>
  <common-layout title="物料分类管理">
    <!-- 标题+操作按钮区 -->
    <template #header-buttons>
      <el-button type="primary" @click="openAddDialog('firstLevel')">
        <el-icon><Plus /></el-icon>
        <span>添加一级分类</span>
      </el-button>
      <el-button type="primary" @click="openAddDialog('secondLevel')">
        <el-icon><Plus /></el-icon>
        <span>添加二级分类</span>
      </el-button>
    </template>

    <!-- 搜索区域 -->
    <template #search-form>
      <el-form :model="searchForm" class="search-form" :inline="true">
        <div class="basic-search">
          <el-form-item label="分类编号" style="width: 260px;">
            <el-input v-model="searchForm.code" placeholder="请输入分类编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="分类名称" style="width: 260px;">
            <el-input v-model="searchForm.name" placeholder="请输入分类名称" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchCategory" style="margin-right: 10px;">
              <el-icon><Search /></el-icon>
              <span>搜索</span>
            </el-button>
            <el-button @click="resetSearch" style="margin-right: 10px;">
              <el-icon><Refresh /></el-icon>
              <span>重置</span>
            </el-button>
            <el-button type="text" @click="toggleAdvancedSearch">
              {{ searchForm.expanded ? '收起查询条件' : '展开查询条件' }}
            </el-button>
          </el-form-item>
        </div>

        <!-- 高级搜索区域 -->
        <div v-if="searchForm.expanded" class="advanced-search">
          <el-form-item label="计量单位" style="width: 260px;">
            <el-input v-model="searchForm.unit" placeholder="请输入计量单位" clearable></el-input>
          </el-form-item>
          <el-form-item label="流水号长度" style="width: 260px;">
            <el-input v-model.number="searchForm.serialLength" placeholder="请输入流水号长度" type="number" clearable></el-input>
          </el-form-item>
          <el-form-item label="供应方式" style="width: 260px;">
            <el-select v-model="searchForm.supplyMethod" placeholder="请选择供应方式" clearable>
              <el-option label="请选择" :value="undefined" />
              <el-option label="自制" value="自制" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" style="width: 260px;">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="请选择" :value="undefined" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
        </div>
      </el-form>
    </template>

    <!-- 数据区 -->
    <template #data-content>
      <el-card shadow="hover">
        <el-tree
          v-loading="loading"
          :data="allCategories"
          default-expand-all
          node-key="Id"
          :props="treeProps"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span :class="data.Status === 0 ? 'text-disabled' : ''">
                {{ node.label }} ({{ data.CategoryCode }})
                <el-tag v-if="data.Status === 0" size="small" type="danger" style="margin-left: 10px;">已禁用</el-tag>
              </span>
              <div class="button-group">
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="() => handleDetailClick(data)"
                  style="margin-right: 5px;"
                >
                  详情
                </el-button>
                <el-button
                  type="warning"
                  size="small"
                  @click.stop="() => openEditDialog(data, node.level === 1 ? 'firstLevel' : 'secondLevel')"
                  style="margin-right: 5px;"
                >
                  编辑
                </el-button>
                <el-button
                  :type="data.Status === 1 ? 'info' : 'success'"
                  size="small"
                  @click.stop="() => toggleStatus(data, node.level === 1 ? 'firstLevel' : 'secondLevel')"
                  style="margin-right: 5px;"
                >
                  {{ data.Status === 1 ? '禁用' : '启用' }}
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click.stop="() => deleteCategory(data, node.level === 1 ? 'firstLevel' : 'secondLevel')"
                >
                  删除
                </el-button>
              </div>
            </span>
          </template>
        </el-tree>
      </el-card>
    </template>
  </common-layout>
    
    <!-- 分类详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="分类详情"
      width="500px"
    >
      <div v-if="selectedCategory" class="category-detail">
        <el-descriptions title="分类信息" :column="1">
          <el-descriptions-item label="分类编号">{{ selectedCategory.CategoryCode }}</el-descriptions-item>
          <el-descriptions-item label="分类名称">{{ selectedCategory.CategoryName }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedCategory.Unit" label="计量单位">{{ selectedCategory.Unit }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedCategory.SerialLength" label="流水号长度">{{ selectedCategory.SerialLength }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedCategory.SupplyMethod" label="供应方式">{{ selectedCategory.SupplyMethod }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ selectedCategory.Status === 1 ? '启用' : '禁用' }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedCategory.FirstLevelCategoryId" label="一级分类">
            {{ selectedCategory.FirstLevelCategory?.CategoryName || '无' }} ({{ selectedCategory.FirstLevelCategory?.CategoryCode || '' }})
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加分类' : '编辑分类'"
      width="500px"
    >
      <el-form
        ref="categoryForm"
        :model="currentCategory"
        label-width="100px"
        style="margin-top: 20px;"
      >
        <template v-if="categoryType === 'firstLevel'">
          <el-form-item label="分类编号" prop="CategoryCode" :rules="[{ required: true, message: '请输入分类编号', trigger: 'blur' }]">
            <el-input v-model="currentCategory.CategoryCode" placeholder="请输入分类编号" :disabled="dialogType === 'edit'" />
          </el-form-item>
          <el-form-item label="分类名称" prop="CategoryName" :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }]">
            <el-input v-model="currentCategory.CategoryName" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="状态" prop="Status">
            <el-select v-model="currentCategory.Status" placeholder="请选择状态" clearable>
              <el-option label="请选择" :value="undefined" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="分类编号" prop="CategoryCode" :rules="[{ required: true, message: '请输入分类编号', trigger: 'blur' }]">
            <el-input v-model="currentCategory.CategoryCode" placeholder="请输入分类编号" :disabled="dialogType === 'edit'" />
          </el-form-item>
          <el-form-item label="分类名称" prop="CategoryName" :rules="[{ required: true, message: '请输入分类名称', trigger: 'blur' }]">
            <el-input v-model="currentCategory.CategoryName" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="一级分类" prop="FirstLevelCategoryId" :rules="[{ required: true, message: '请选择一级分类', trigger: 'change' }]">
            <el-select v-model="currentCategory.FirstLevelCategoryId" placeholder="请选择一级分类">
              <el-option
                v-for="mainCategory in mainCategories"
                :key="mainCategory.Id"
                :label="`${mainCategory.CategoryName} (${mainCategory.CategoryCode})`"
                :value="mainCategory.Id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="物料描述" prop="MaterialDescription">
            <el-input v-model="currentCategory.MaterialDescription" placeholder="请输入物料描述" />
          </el-form-item>
          <el-form-item label="计量单位" prop="Unit">
            <el-input v-model="currentCategory.Unit" placeholder="请输入计量单位" />
          </el-form-item>
          <el-form-item label="安全库存" prop="SafetyStock">
            <el-input
              v-model.number="currentCategory.SafetyStock"
              placeholder="请输入安全库存"
              type="number"
              min="0"
            />
          </el-form-item>
          <el-form-item label="状态" prop="Status">
            <el-select v-model="currentCategory.Status" placeholder="请选择状态" clearable>
              <el-option label="请选择" :value="undefined" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">确定</el-button>
      </template>
    </el-dialog>
</template>

<style scoped>


.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.buttons {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.basic-search {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.advanced-search {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #e4e7ed;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.custom-tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.button-group {
  display: flex;
  gap: 5px;
}

.text-disabled {
  color: #909399;
}

.category-detail {
  padding: 10px;
}
</style>